package com.woniuxy.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.woniuxy.common.ConstantData;
import com.woniuxy.common.RedisKey;
import com.woniuxy.controller.form.StoreRegisterSearchForm;
import com.woniuxy.controller.form.StoreRegisterForm;
import com.woniuxy.controller.form.StoreRegisterUpdateForm;
import com.woniuxy.controller.form.StoreRegisterUpdateStatusForm;
import com.woniuxy.dao.DietTimeConfigMapper;
import com.woniuxy.dao.StoreInfoMapper;
import com.woniuxy.entity.Account;
import com.woniuxy.entity.DietTimeConfig;
import com.woniuxy.entity.StoreInfo;
import com.woniuxy.entity.StoreRegister;
import com.woniuxy.dao.StoreRegisterMapper;
import com.woniuxy.exception.storeRegister.StoreRegisterException;
import com.woniuxy.exception.storeRegister.StoreRegisterExceptionCode;
import com.woniuxy.service.AccountService;
import com.woniuxy.service.DietTimeConfigService;
import com.woniuxy.service.StoreRegisterService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniuxy.service.dto.StoreInfoForEsDto;
import com.woniuxy.service.dto.StoreRegisterDto;
import com.woniuxy.service.dto.WoniuPageDto;
import com.woniuxy.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 商家注册表 服务实现类
 * </p>
 *
 * @author zz
 * @since 2023年06月13日
 */
@Service
public class StoreRegisterServiceImpl extends ServiceImpl<StoreRegisterMapper, StoreRegister> implements StoreRegisterService {

    @Autowired
    private StoreRegisterMapper mapper;
    @Autowired
    private StoreInfoMapper infoMapper;
    @Autowired
    private ElasticsearchRestTemplate template;
    @Autowired
    private AccountService accountService;
    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private DietTimeConfigService dietTimeConfigService;


    /**
     * 添加商品注册表
     * @param form
     * @param accountId
     */
    @Override
    public void addRegister(StoreRegisterForm form,Integer accountId) {
        QueryWrapper<StoreRegister> queryWrapper = new QueryWrapper<StoreRegister>().eq("accountId", accountId);
        StoreRegister one = mapper.selectOne(queryWrapper);
        if(one!=null){
            throw new StoreRegisterException(StoreRegisterExceptionCode.REGISTER_IS_EXIST);
        }
        StoreRegister register = BeanUtil.toBean(form, StoreRegister.class);
        register.setStatus(ConstantData.STORE_REGISTER_STATE_NOT_CHECK);
        register.setAccountId(accountId.longValue());
        register.setDeleteFlag(ConstantData.STATE_NORMAL);
        register.setCreateDate(LocalDateTime.now());

        mapper.insert(register);
    }

    /**
     * 更新商铺注册信息
     * @param form
     * @param accountId
     * @return
     */
    @Override
    public StoreRegister updateMessage(StoreRegisterUpdateForm form, Integer accountId) {
        QueryWrapper<StoreRegister> wrapper = new QueryWrapper<>();
        wrapper.eq("accountId",accountId);
        StoreRegister storeRegister = mapper.selectOne(wrapper);
        StoreRegister register= BeanUtil.toBean(form, StoreRegister.class);
        register.setRejectReason("");
        register.setUpdateDate(LocalDateTime.now());
        register.setStatus(ConstantData.STORE_REGISTER_STATE_NOT_CHECK);
        mapper.updateById(register);
        return register;
    }

    /**
     * 检测商铺名重复
     * @param storeName
     * @return
     */
    @Override
    public String check(String storeName) {
        QueryWrapper<StoreRegister> registerQueryWrapper = new QueryWrapper<>();
        registerQueryWrapper.eq("storeName",storeName).notIn("status",ConstantData.STORE_REGISTER_STATE_NOT_PASS);
        StoreRegister storeRegister = mapper.selectOne(registerQueryWrapper); //查询是否有重名的注册表
        if(storeRegister!=null){
          return "商铺名称已被使用";
        }
        return "商铺名称可用";
    }

    /**
     * 通过状态查询注册/查所有注册
     * @param
     * @return
     */
    @Override
    public WoniuPageDto searchByStatus(StoreRegisterSearchForm form) {
        Page<StoreRegister> page = new Page<>(form.getCurrent() == null ? 1 : form.getCurrent(), form.getSize() == null ? 20 : form.getSize());
        QueryWrapper<StoreRegister> wrapper = new QueryWrapper<>();
        if(form.getStatus()==null ||form.getStatus().equals("")){
            wrapper.eq("deleteFlag", ConstantData.STATE_NORMAL);
        }else {
            wrapper.eq("status", form.getStatus()).eq("deleteFlag", ConstantData.STATE_NORMAL);
        }
        Page<StoreRegister> registerPage = mapper.selectPage(page, wrapper);
//        if (registerPage.getRecords().size()== 0 || registerPage == null) {
//            throw new StoreRegisterException(StoreRegisterExceptionCode.REGISTER_COUNT_ZERO);
//        }
        List<StoreRegisterDto> dtos = new ArrayList<>();
        for (StoreRegister register : registerPage.getRecords()) {
            StoreRegisterDto dto = BeanUtil.toBean(register, StoreRegisterDto.class);
            if(register.getStatus()==ConstantData.STORE_REGISTER_STATE_NOT_CHECK){
                dto.setStatusName("待审核");
            }else if(register.getStatus()==ConstantData.STORE_REGISTER_STATE_NOT_PASS){
                dto.setStatusName("未通过");
            }else if(register.getStatus()==ConstantData.STORE_REGISTER_STATE_PASS){
                dto.setStatusName("已通过");
            }
            dtos.add(dto);
        }
        WoniuPageDto pageDto = BeanUtil.toBean(page, WoniuPageDto.class);
        pageDto.setList(dtos);
        return pageDto;
    }

    /**
     * 审核注册表
     * @param form
     * @return
     */
    @Override
    public StoreRegister updateStatus(StoreRegisterUpdateStatusForm form) throws Exception {
        StoreRegister register = mapper.selectOne(new QueryWrapper<StoreRegister>().eq("accountId", form.getAccountId()));
        if(register==null){
            throw new StoreRegisterException(StoreRegisterExceptionCode.REGISTER_IS_NOT_EXIST);
        }
        if(register.getStatus()==ConstantData.STORE_REGISTER_STATE_PASS && register.getStatus()==form.getNewStatus()){
            throw new StoreRegisterException(StoreRegisterExceptionCode.REGISTER_IS_CHECKED);
        }
        if(register.getStatus()==ConstantData.STORE_REGISTER_STATE_NOT_PASS && register.getStatus()==form.getNewStatus()){
            throw new StoreRegisterException(StoreRegisterExceptionCode.REGISTER_IS_CHECKED);
        }
        register.setStatus(form.getNewStatus());
        if(form.getNewStatus()==ConstantData.STORE_REGISTER_STATE_NOT_PASS){
            register.setRejectReason(form.getRejectReason());
        }
        if(form.getNewStatus()==ConstantData.STORE_REGISTER_STATE_PASS){
            StoreInfo storeInfo = BeanUtil.toBean(register, StoreInfo.class);
            storeInfo.setUserAccount(register.getAccountId().toString());
            storeInfo.setDeleteFlag(ConstantData.STATE_NORMAL);
            storeInfo.setStoreScore(0.0);
            storeInfo.setDishesScore(0.0);
            storeInfo.setDphScore(0.0);
            storeInfo.setLogo("https://bucket-book-fjx.oss-cn-chengdu.aliyuncs.com/18b18ccd-4271-401b-b397-4f47d1f03113.png");
            storeInfo.setAutoAccept(ConstantData.AUTO_ACCEPT);
            storeInfo.setStatus(ConstantData.STORE_INFO_STATUS_LIVE);
            storeInfo.setStoreStatus(ConstantData.STORE_INFO_STATUS_OPEN);
            //新增商家数据库
            infoMapper.insert(storeInfo);
            StoreInfoForEsDto esDto = BeanUtil.toBean(storeInfo, StoreInfoForEsDto.class);
            esDto.setFood(null);
            esDto.setCount(0);
            //es
            template.save(esDto);
            Account account = accountService.getById(form.getAccountId());
            account.setRole("正式商家");
            //新增账号数据库
            accountService.saveOrUpdate(account);


            //新增配送表
            DietTimeConfig dietTimeConfig = new DietTimeConfig();
            dietTimeConfig.setStoreId(storeInfo.getId());
            dietTimeConfig.setDietName("早餐");
            LocalTime morningStart = LocalTime.of(7, 30);
            LocalTime morningEnd = LocalTime.of(9, 30);
            dietTimeConfig.setStartTime(morningStart);
            dietTimeConfig.setEndTime(morningEnd);

            DietTimeConfig dietTimeConfig2 = new DietTimeConfig();
            dietTimeConfig2.setStoreId(storeInfo.getId());
            dietTimeConfig2.setDietName("午餐");
            LocalTime lunchStart = LocalTime.of(11, 30);
            LocalTime lunchEnd = LocalTime.of(1, 30);
            dietTimeConfig2.setStartTime(lunchStart);
            dietTimeConfig2.setEndTime(lunchEnd);

            DietTimeConfig dietTimeConfig3 = new DietTimeConfig();
            dietTimeConfig3.setStoreId(storeInfo.getId());
            dietTimeConfig3.setDietName("晚餐");
            LocalTime dinnerStart = LocalTime.of(17, 30);
            LocalTime dinnerEnd = LocalTime.of(20, 30);
            dietTimeConfig3.setStartTime(dinnerStart);
            dietTimeConfig3.setEndTime(dinnerEnd);

            dietTimeConfigService.saveOrUpdate(dietTimeConfig);
            dietTimeConfigService.saveOrUpdate(dietTimeConfig2);
            dietTimeConfigService.saveOrUpdate(dietTimeConfig3);

            //新增redis月销键
            redisUtil.zincrby(RedisKey.getStoreSaleKey(),storeInfo.getId().toString(),0);

        }
        mapper.updateById(register);//改注册表
        return register;
    }

    @Override
    public Integer checkFormed(Integer accountId) {
        StoreRegister storeRegister = mapper.selectOne(new QueryWrapper<StoreRegister>().eq("accountId", accountId));
        if(storeRegister==null){
            return 1;
        }else if(storeRegister.getStatus()==ConstantData.STORE_REGISTER_STATE_NOT_CHECK){
            return 3;
        }else if(storeRegister.getStatus()==ConstantData.STORE_REGISTER_STATE_NOT_PASS){
            return 2;
        }
        return null;
    }
}
